﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Domain.Repositories;

namespace OpenPasteSpider.sourcemodel
{

    /// <summary>
    /// 上载配置
    ///</summary>
    [TypeFilter(typeof(RoleAttribute), Arguments = new object[] { "data", "view" })]
    public class AsyncConfigAppService : OpenPasteSpiderAppService
    {

        private IOpenPasteSpiderDbContext _dbContext;
        public AsyncConfigAppService(IOpenPasteSpiderDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="page"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<PagedResultDto<AsyncConfigListDto>> GetListAsync(int page = 1, int size = 20)
        {

            var query = _dbContext.AsyncConfig.Where(t => 1 == 1);

            var pagedResultDto = new PagedResultDto<AsyncConfigListDto>();
            pagedResultDto.TotalCount = await query.CountAsync();


            var querylist = await (from a in query
                                   join b in _dbContext.ServiceInfo on a.ServiceId equals b.Id into c
                                   from d in c.DefaultIfEmpty()
                                   select new AsyncConfigListDto
                                   {
                                       FileModel = d.FileModel,
                                       FileName = a.FileName,
                                       Id = a.Id,
                                       Ignore = a.Ignore,
                                       IsDirectory = a.IsDirectory,
                                       IsEnable = a.IsEnable,
                                       Name = d.Name
                                   }).OrderByDescending(x=>x.Id).OrderBy(x => x.Id).Page(page, size).ToListAsync();
            pagedResultDto.Items = querylist;
            return pagedResultDto;
        }

        /// <summary>
        /// 根据ID获取单项上载配置
        ///</summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public AsyncConfigDto GetByIdAsync(int id)
        {
            var query = _dbContext.AsyncConfig.Where(t => t.Id == id)
            .FirstOrDefault();
            var temList = ObjectMapper.Map<AsyncConfig, AsyncConfigDto>(query);
            return temList;
        }

        /// <summary>
        /// 根据ID获取待更新单项信息上载配置
        ///</summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public AsyncConfigUpdateDto GetInfoForUpdateAsync(int id)
        {
            var query = _dbContext.AsyncConfig.Where(t => t.Id == id)
            .FirstOrDefault();
            var temList = ObjectMapper.Map<AsyncConfig, AsyncConfigUpdateDto>(query);
            return temList;
        }


        /// <summary>
        /// 添加一个上载配置
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<AsyncConfigDto> CreateItemAsync(AsyncConfigAddDto input)
        {

            var newu = ObjectMapper.Map<AsyncConfigAddDto, AsyncConfig>(input);

            //var _service = _dbContext.ServiceInfo.Where(x => x.Id == input.ServiceId).AsNoTracking().FirstOrDefault();
            //if (_service != null && _service != default)
            //{
            //    newu.FileModel = _service.FileModel;
            //}
            //else
            //{
            //    throw new PasteException("选择的服务无效，请重新选择！");
            //}

            //添加自定义
            _dbContext.Add(newu);
            await _dbContext.SaveChangesAsync();
            //var updated = await _repository.InsertAsync(newu,true);
            var backinfo = ObjectMapper.Map<AsyncConfig, AsyncConfigDto>(newu);
            return backinfo;
        }
        /// <summary>
        /// 更新一个上载配置
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<AsyncConfigDto> UpdateItemAsync(AsyncConfigUpdateDto input)
        {
            var info = await _dbContext.AsyncConfig.Where(x => x.Id == input.Id).FirstOrDefaultAsync();
            if (info == null || info == default)
            {
                throw new UserFriendlyException("需要查询的信息不存在", "404");
            }



            ObjectMapper.Map<AsyncConfigUpdateDto, AsyncConfig>(input, info);
            
            //var _service = _dbContext.ServiceInfo.Where(x => x.Id == input.ServiceId).AsNoTracking().FirstOrDefault();
            //if (_service != null && _service != default)
            //{
            //    info.FileModel = _service.FileModel;
            //}
            //else
            //{
            //    throw new PasteException("选择的服务无效，请重新选择！");
            //}
            //var updated = await _repository.UpdateAsync(newu);
            await _dbContext.SaveChangesAsync();
            var backinfo = ObjectMapper.Map<AsyncConfig, AsyncConfigDto>(info);
            return backinfo;
        }
    }
}
